// const Events=require('events');
const WS = require("ws");
const queue = require('queue');
const mongoose = require('mongoose');
const config=require('../config');
class GameServer{
    constructor(){
        require('../db/mongodb').load();
        this.ip=!!process.argv[2]?process.argv[2]:'127.0.0.1';
        this.port=!!process.argv[3]?process.argv[3]:6500;
        this.type=!!process.argv[4]?process.argv[4]:0; //类型  0代表随机乱斗服务器，1代表组队匹配服务器，2代表开房服务器
        this.status=0; //服务器状态 0可加入 1不可加入
        this.ws=null;
        this.listen();
        this.queue=queue({autostart:true});
        this.queue.pushTry=function(fun){
            this.queue.push(function(){
                try{
                    this.fun();
                }catch(e){
                    console.error(e);
                    const mongoose = require('mongoose');
                    const ErrorModel=mongoose.models['Error'];
                    ErrorModel.create({
                        stack:JSON.stringify(e.stack)
                    });
                }
            }.bind({fun:fun}))
        }.bind(this);
    }
    listen(){
        if(config.debug){
            this.ws = new WS.Server({
                port: parseInt(process.argv[3])
            });
        }else{
            const https = require('https');
            const fs=require('fs');
            const server = new https.createServer({
                key: fs.readFileSync('./cert/ppt/215093671130336.key'),
                cert: fs.readFileSync('./cert/ppt/215093671130336.pem'),
            });
            this.ws = new WS.Server({server});
            server.listen(parseInt(process.argv[3]));
        }

        this.ws.broadcast=function(data){
            this.ws.clients.forEach(function(client) {
                if(client.readyState == 1){
                    console.log('发送消息',data,client.id);
                    client.send(data);
                }
            });
        }.bind(this);
        this.ws.on('connection', function(socket) {
            console.log('新连接');
            socket.on('message', async function(data) {
                //console.log('收到信息：',data);
                try{
                    let dataObj=JSON.parse(data);
                    switch(dataObj.r){
                        //登陆绑定
                        case 'init':{

                            break;
                        }
                        case 'login':{
                            try{
                                await this.userLogin(dataObj._id,dataObj.token,socket);
                            }catch(e){
                                const ErrorModel=mongoose.models['Error'];
                                ErrorModel.create({
                                    stack:JSON.stringify(e.stack)
                                });
                            }
                            break;
                        }
                        default:{
                            socket.emit('method',dataObj);
                            break;
                        }
                    }
                }catch(e){
                    console.error(e.message);
                }
            }.bind(this));
            socket.on('ping',function(data){
                socket.pong(data);
                console.log('收到ping：',data);
            });
            socket.on('pong',function(data){
                console.log('收到pong：',data);
            });
        }.bind(this));
    }
}

new GameServer();